package com.zq.it.service.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.zq.it.dao.admin.AcademyDao;
import com.zq.it.dao.admin.AdminDao;
import com.zq.it.dao.admin.ChapterDao;
import com.zq.it.dao.admin.CourseDao;
import com.zq.it.dao.admin.CourseManageDao;
import com.zq.it.dao.admin.MajorDao;
import com.zq.it.dao.admin.MessageDao;
import com.zq.it.dao.admin.NetCourseDao;
import com.zq.it.dao.admin.StudentDao;
import com.zq.it.dao.admin.TAddressDao;
import com.zq.it.dao.admin.TClassDao;
import com.zq.it.dao.admin.TeacherDao;
import com.zq.it.dao.admin.UserDao;
import com.zq.it.dao.common.PageConfig;
import com.zq.it.dao.exam.PageDAO;
import com.zq.it.dao.exam.TClassPaperDAO;
import com.zq.it.dao.exam.TClassTaskDAO;
import com.zq.it.dao.exam.TCourseWareDAO;
import com.zq.it.dao.exam.TExamDAO;
import com.zq.it.dao.exam.TExamResultDAO;
import com.zq.it.dao.exam.TNoteDAO;
import com.zq.it.dao.exam.TOptionsDAO;
import com.zq.it.dao.exam.TPaperDAO;
import com.zq.it.dao.exam.TPaperDetailDAO;
import com.zq.it.dao.exam.TPaperSectionDAO;
import com.zq.it.dao.exam.TQuestionDbDAO;
import com.zq.it.dao.exam.TQuestionsDAO;
import com.zq.it.dao.exam.TStudentTaskDAO;
import com.zq.it.dao.exam.TTaskDAO;
import com.zq.it.dao.exam.TTaskmodelDAO;
import com.zq.it.dao.impl.BaseDao;
import com.zq.it.pojo.Academy;
import com.zq.it.pojo.Course;
import com.zq.it.pojo.Major;
import com.zq.it.pojo.Message;
import com.zq.it.pojo.TClass;
import com.zq.it.pojo.exam.data.ObjectData;
import com.zq.it.service.validate.Validate;
import com.zq.it.tool.FileType;

//import java.util.Date;

public class BaseServiceImpl {

	@Resource
	private UserDao userDao;
	@Resource
	private BaseDao baseDao;
	@Resource
	private AdminDao adminDao;
	@Resource
	private AcademyDao academyDao;
	@Resource
	private StudentDao studentDao;
	@Resource
	private MessageDao messageDao;
	@Resource
	private TeacherDao teacherDao;
	@Resource
	private ChapterDao chapterDao;
	@Resource
	private TClassDao classDao;
	@Resource
	private TAddressDao addressDao;
	@Resource
	private CourseDao courseDao;
	@Resource
	private NetCourseDao netCourseDao;
	@Resource
	private MajorDao majorDao;
	@Resource
	private CourseManageDao courseManageDao;
	@Resource
	protected TClassPaperDAO classPaperDAO;
	@Resource
	protected TCourseWareDAO courseWareDAO;
	@Resource
	protected TExamResultDAO examResultDAO;
	@Resource
	protected TExamDAO examDAO;
	@Resource
	protected TNoteDAO noteDAO;
	@Resource
	protected TOptionsDAO optionsDAO;
	@Resource
	protected TPaperDAO paperDAO;
	@Resource
	protected TPaperDetailDAO paperDetailDAO;
	@Resource
	protected TQuestionDbDAO questionDbDAO;
	@Resource
	protected TQuestionsDAO questionsDAO;
	@Resource
	protected TStudentTaskDAO studentTaskDAO;
	@Resource
	protected TTaskDAO taskDAO;
	@Resource
	protected TTaskmodelDAO taskmodelDAO;

	@Resource
	protected PageDAO pageDAO;
	@Resource
	protected TClassTaskDAO classTaskDAO;
	@Resource
	protected TPaperSectionDAO paperSectionDAO;
	@Resource
	protected Validate validate;

	public ObjectData getListByPage(PageConfig config) {
		return pageDAO.getData(config);
	}

	public String getRealPath(String path) {
		return ServletActionContext.getServletContext().getRealPath(path);
	}

	/**
	 * 递归删除非空文件夹
	 * 
	 * @param dir
	 * @return
	 */
	public boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		return dir.delete();
	}

	public BaseDao getBaseDao() {
		return baseDao;
	}
	public AdminDao getAdminDao() {
		return adminDao;
	}
	public void setAdminDao(AdminDao adminDao) {
		this.adminDao = adminDao;
	}

	public CourseManageDao getCourseManageDao() {
		return courseManageDao;
	}

	public MajorDao getMajorDao() {
		return majorDao;
	}
	public void setMajorDao(MajorDao majorDao) {
		this.majorDao = majorDao;
	}
	public NetCourseDao getNetCourseDao() {
		return netCourseDao;
	}
	public TeacherDao getTeacherDao() {
		return teacherDao;
	}

	public AcademyDao getAcademyDao() {
		return academyDao;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public StudentDao getStudentDao() {
		return studentDao;
	}

	public MessageDao getMessageDao() {
		return messageDao;
	}

	public ChapterDao getChapterDao() {
		return chapterDao;
	}

	public TClassDao getClassDao() {
		return classDao;
	}

	public TAddressDao getAddressDao() {
		return addressDao;
	}

	public CourseDao getCourseDao() {
		return courseDao;
	}

	public void closeIo(OutputStream out) {
		if (out != null) {
			try {
				out.flush();
				out.close();
			} catch (IOException ioe) {
				System.out.println("关闭输出流异常！");
			}
		}
	}

	public File createFile(String parentURL, String name, FileType fileType) {
		File file = new File(parentURL, name + fileType);
		if (!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return file;
	}

	public void writeStrContent(String content, File file) {

		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(content.getBytes());
			// closeIo(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			/* closeIo(out); */
		} finally {
			closeIo(out);
		}

	}

	public void deleteFile(String fileUrl) {
		File file = new File(fileUrl);
		if (file.exists()) {
			file.delete();
		}
	}

	public Collection<Message> getCollection(String[] msgIdGroups) {
		Collection<Message> collection = new ArrayList<Message>();
		for (int i = 0; i < msgIdGroups.length; i++) {
			collection.add(new Message(Integer.parseInt(msgIdGroups[i])));
		}
		return collection;
	}
	
	public String[] getIdGroups(String str) {
		return str.split(":");
	}

	// 导入xlsx格式Excel文档方法(适用于EXCEL2010)

	public String importxlsxFile(File file) {
		String dataStr = "";
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(file));
			XSSFSheet sheet = workbook.getSheet("Sheet1"); // 获取工作簿
			int rows = sheet.getPhysicalNumberOfRows();
			for (int i = 1; i < rows; i++) {
				XSSFRow row = sheet.getRow(i); // 得到一行
				if (null != row && null != row.getCell(0)
						&& !"".equals(row.getCell(0).getRawValue())) {
					for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
						XSSFCell cell = row.getCell(j);
						switch (cell.getCellType()) {
							case XSSFCell.CELL_TYPE_STRING :
								dataStr += cell.getStringCellValue();
								break;
							case XSSFCell.CELL_TYPE_NUMERIC :
								if (DateUtil.isCellDateFormatted(cell)) {

									// result = sdf.format(date);
									// double d = cell.getNumericCellValue();
									// String
									// dateStr=DateFormat.getDateInstance(DateFormat.SHORT).format(DateUtil.getJavaDate(d));
									dataStr += new SimpleDateFormat()
											.format(DateUtil.getJavaDate(cell
													.getNumericCellValue()));
								} else {
									int value = (int) cell
											.getNumericCellValue();

									dataStr += value;
								}
								break;
							case XSSFCell.CELL_TYPE_FORMULA : // 公式
								dataStr += new SimpleDateFormat("YYYY-MM-dd")
										.format(DateUtil.getJavaDate(
												cell.getNumericCellValue()));
								break;
						}
						dataStr += ":";
					}
				}
				dataStr += ";";
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dataStr;
	}

	public ByteArrayOutputStream exportToExcel(List<?> list, String[] colName,
			String[] propName, String className) {
		XSSFWorkbook workbook = new XSSFWorkbook();
		XSSFCellStyle cellStyle = workbook.createCellStyle();
		XSSFSheet sheet = workbook.createSheet("sheet1");
		XSSFRow row = sheet.createRow(0);
		Class<?> c = null; // 声明class 类
		int arrayLength = propName.length; // 存储列数量值
		Method[] methods = new Method[arrayLength]; // 存储方法

		try {
			c = Class.forName(className); // 创建对象
			for (short i = 0; i < arrayLength; i++) {
				XSSFCell cell = row.createCell(i);
				cell.setCellStyle(cellStyle);
				XSSFRichTextString text = new XSSFRichTextString(colName[i]);
				cell.setCellValue(text);
				methods[i] = c.getMethod(
						"get" + propName[i].substring(0, 1).toUpperCase()
								+ propName[i].substring(1),
						new Class[]{}); // 向数组中添加方法
			}
		} catch (Exception e) {
			System.err.print(e);
		}

		Iterator it = list.iterator();
		int index = 0;
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			Object entity = it.next();
			for (short i = 0; i < propName.length; i++) {
				XSSFCell cell = row.createCell(i); // 根据数据域的数量创建表格一行中的数量
				try {
					Object value = methods[i].invoke(entity, new Object[]{}); // 出去数据域中的值
					String textValue = null;
					if (value instanceof Date) {
						SimpleDateFormat sdf = new SimpleDateFormat(
								"YYYY-MM-dd");
						textValue = sdf.format((Date) value);
					} else if (value instanceof Academy) {
						Academy acmy = (Academy) value;
						textValue = acmy.getAcademyName().toString();
					} else if (value instanceof Major) {
						textValue = ((Major) value).getMajorName();
					} else if (value instanceof Course) {
						textValue = ((Course) value).getCourseName();
					} else if (value == null) {
						textValue = "未知";
					} else if (value instanceof TClass) {
						textValue = ((TClass) value).getClassName();
					} else {
						textValue = value.toString();
					}
					// 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
					if (textValue != null) {
						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
						Matcher matcher = p.matcher(textValue);
						if (matcher.matches())
							cell.setCellValue(Double.parseDouble(textValue));
						else {
							XSSFRichTextString richString = new XSSFRichTextString(
									textValue);
							XSSFFont font3 = workbook.createFont();
							richString.applyFont(font3);
							cell.setCellValue(richString);
						}
					}
				} catch (Exception e) {
					System.out.println(e);
				}
			}
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			workbook.write(os);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return os;
	}

	/**
	 * 视频转码
	 * 
	 * @param ffmpegPath
	 *            转码工具的存放路径
	 * @param sourceFilePath
	 *            用于指定要转换格式的文件,要截图的视频源文件
	 * @param codcFilePath
	 *            格式转换后的的文件保存路径
	 * @param mediaPicPath
	 *            截图保存路径
	 * @return
	 * @throws Exception
	 */
	public void executeCodecs(String ffmpegPath, String sourceFilePath,
			String mediaPicPath) throws Exception {

		// 创建一个List集合来保存转换视频文件为flv格式的命令
		/*
		 * List<String> convert = new ArrayList<String>();
		 * convert.add(ffmpegPath); // 添加转换工具路径 convert.add("-i"); //
		 * 添加参数＂-i＂，该参数指定要转换的文件 convert.add(sourceFilePath); // 添加要转换格式的视频文件的路径
		 * convert.add("-qscale"); //指定转换的质量 convert.add("6");
		 * convert.add("-ab"); //设置音频码率 convert.add("64"); convert.add("-ac");
		 * //设置声道数 convert.add("2"); convert.add("-ar"); //设置声音的采样频率
		 * convert.add("22050"); convert.add("-r"); //设置帧频 convert.add("24");
		 * convert.add("-y"); // 添加参数＂-y＂，该参数指定将覆盖已存在的文件
		 * convert.add(codcFilePath);
		 */
		// 创建一个List集合来保存从视频中截取图片的命令

		List<String> cmd = new LinkedList<String>();
		cmd.add(ffmpegPath);
		cmd.add("-y");
		cmd.add("-i");
		cmd.add(sourceFilePath);
		cmd.add("-ss");
		cmd.add("8.0");
		cmd.add("-vframes");
		cmd.add("1");
		cmd.add("-r");
		cmd.add("1");
		cmd.add("-ac");
		cmd.add("1");
		cmd.add("-ab");
		cmd.add("2");
		cmd.add("-s");
		cmd.add("256*243");
		cmd.add("-f");
		cmd.add("image2");
		cmd.add(mediaPicPath);
		ProcessBuilder builder = new ProcessBuilder();
		try {
			builder.command(cmd); // 视频截取
			builder.redirectErrorStream(true);
			builder.start();
			// 如果此属性为 true，则任何由通过此对象的 start() 方法启动的后续子进程生成的错误输出都将与标准输出合并，
			// 因此两者均可使用 Process.getInputStream() 方法读取。这使得关联错误消息和相应的输出变得更容易
			/*
			 * builder.command(convert); //视频转换
			 * builder.redirectErrorStream(true); builder.start();
			 */
			/*
			 * BufferedReader bfr=new BufferedReader(new
			 * InputStreamReader(process.getInputStream())); String line=null;
			 * while((line = bfr.readLine())!= null){} process.waitFor();
			 */
			// return true;

		} catch (Exception e) {
			System.out.println(e);
			// return false;
		}

	}
	// 导入xls格式Excel文档方法
}
